package cl.golive.d2menu.utils.dbUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 *
 * @author whyem
 */
public final class DataBaseConn
{
    private Connection connection;
    private String driver;
    private String url;
    private String user;
    private String password;

    public DataBaseConn() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        loadInitProperties();
        //loadInitPropertiesHardCoded();
        init();
    }

    private void loadInitProperties() throws IOException {
        Properties props = new Properties();
        props.load(new FileInputStream("../db-config.properties"));
        this.driver = props.getProperty("driver");
        this.url = props.getProperty("url");
        this.user = props.getProperty("user");
        this.password = props.getProperty("password");

        System.out.println("> Url: "+url);
        System.out.println("> User: "+user);
        System.out.println("> Password: "+password);
    }

     private void loadInitPropertiesHardCoded() throws IOException {
        this.driver = "com.mysql.jdbc.Driver";
        this.url = "jdbc:mysql://192.168.1.110/d2menu_bd";
        this.user = "root";
        this.password = "";
    }

    private void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class.forName(this.driver).newInstance();
    }

    public void openConnection() throws SQLException {
        this.connection = DriverManager.getConnection(this.url, this.user, this.password);
    }

    public void closeConnection() throws SQLException {
        this.connection.close();
    }

    public int cudSQL(String query) throws SQLException {
        Statement statement = connection.createStatement();
        return statement.executeUpdate(query);
    }

    public ResultSet selectSQL(String query) throws SQLException {
        Statement statement = connection.createStatement();
        return (ResultSet) statement.executeQuery(query);
    }

}